package com.qinglei.recoup.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.pojo.AddRoomParam;
import com.qinglei.recoup.system.pojo.TimePeriodParam;
import com.qinglei.recoup.system.pojo.RoomPageParam;
import com.qinglei.recoup.system.pojo.RoomShowVO;
import com.qinglei.recoup.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author zxy
 */
@Api(tags = "房间 相关控制器-张-已实现")
@RestController
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RoomService roomService;

    @Autowired
    private BedService bedService;

    @Autowired
    private RadarBedService radarBedService;

    @Autowired
    private FloorService floorService;

    @Autowired
    private BuildingService buildingService;

    @Autowired
    private MonitorTimeService monitorTimeService;

    @Autowired
    private SystemConfigService systemConfigService;

    @ApiOperation(value = "分页查询房间")
    @GetMapping("/showPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "floorId", value = "层id", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页码，从1开始，默认是1", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数，默认20", paramType = "query", dataType = "Integer")
    })
    public CommonRes<IPage<RoomShowVO>> showPageRoom(RoomPageParam roomPageParam) {
        return roomService.showPageroom(roomPageParam);
    }

    @ApiOperation(value = "添加房间")
    @PostMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "buildingId", value = "楼id", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "floorId", value = "层id", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "name", value = "房间名称", paramType = "body", dataType = "String", required = true)})
    public CommonRes addRoom(@RequestBody AddRoomParam addroomParam) {
        Integer integer = roomService.getBaseMapper().selectCount(Wrappers.<Room>lambdaQuery()
                .eq(Room::getFloorId,addroomParam.getFloorId())
                .eq(Room::getName,addroomParam.getName()));
        if (integer > 0){
            return CommonRes.failed("房间名称重复");
        }
        //如果房间为数字自动补零---------------------------------------------------
        if ( null != addroomParam.getName() && !"".equals(addroomParam.getName())) {
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean matches = pattern.matcher(addroomParam.getName()).matches();
            StringBuilder  strb =new StringBuilder();
            if (matches) {
                int length = addroomParam.getName().length();
                int a=4;
                if (length<a) {
                    for (int i = 0; i < a-length; i++) {
                        strb.append("0");
                    }
                    strb.append(addroomParam.getName());
                    addroomParam.setName(strb.toString());
                }
            }
        }
        //----------------------------------------------------------------------
        Room room = new Room();
        BeanUtils.copyProperties(addroomParam,room);
        Floor floor = floorService.getBaseMapper().selectById(addroomParam.getFloorId());
        //离床时间阈值
        room.setOutBedTimeout(floor.getOutBedTimeout());
        room.setOutBedTimeoutUnified(floor.getOutBedTimeoutUnified());
        //监测时间
        room.setMonitorTimeUnified(floor.getMonitorTimeUnified());
        int count = roomService.getBaseMapper().insert(room);
        List<TimePeriodParam> monitorTimeByObjIdandtype = monitorTimeService.getMonitorTimeByObjIdAndType(addroomParam.getFloorId(), SystemConfigService.TYPE_OUT_BED_TIMEOUT);
        if (monitorTimeByObjIdandtype.size() > 0) {
            for (TimePeriodParam mtq : monitorTimeByObjIdandtype) {
                MonitorTime monitorTime = new MonitorTime();
                BeanUtils.copyProperties(mtq, monitorTime);
                monitorTime.setObjId(room.getId());
                monitorTime.setType(SystemConfigService.TYPE_TOUR_TIME);
                monitorTimeService.getBaseMapper().insert(monitorTime);
            }
        }else {
            List<TimePeriodParam> monitorTimeList = systemConfigService.getDefaultMonitorTime();
            for (TimePeriodParam sc : monitorTimeList) {
                MonitorTime monitorTime = new MonitorTime();
                monitorTime.setStartTime(sc.getStartTime());
                monitorTime.setEndTime(sc.getEndTime());
                monitorTime.setObjId(room.getId());
                monitorTime.setType(SystemConfigService.TYPE_TOUR_TIME);
                monitorTimeService.getBaseMapper().insert(monitorTime);
            }
        }
        if (count>0){
            return CommonRes.ok();
        }
        return CommonRes.failed("新增房间失败");
    }

    @ApiOperation(value = "通过房间id查询")
    @GetMapping("/{id}")
    @ApiImplicitParam(name = "id", value = "房间id", paramType = "path", dataType = "Integer")
    public CommonRes<RoomShowVO> getroomById(@PathVariable Integer id) {
        Room room = roomService.getBaseMapper().selectById(id);
        RoomShowVO roomShowVO = new RoomShowVO();
        BeanUtils.copyProperties(room,roomShowVO);
        return CommonRes.ok(roomShowVO);
    }

    @ApiOperation(value = "修改房间信息")
    @PutMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "房间id", paramType = "body", dataType = "Integer",required = true),
            @ApiImplicitParam(name = "name", value = "房间名称", paramType = "body", dataType = "String",required = true)})
    public CommonRes addRadar(@RequestBody RoomShowVO roomShowVO) {
        Room room1 = roomService.getBaseMapper().selectById(roomShowVO.getId());
        Integer integer = roomService.getBaseMapper().selectCount(Wrappers.<Room>lambdaQuery()
                .eq(Room::getFloorId,room1.getFloorId())
                .eq(Room::getName,roomShowVO.getName())
                .last("and id != "+roomShowVO.getId()));
        if (integer > 0){
            return CommonRes.failed("房间名称重复");
        }
        //如果房间为数字自动补零---------------------------------------------------
        if ( null != roomShowVO.getName() && !"".equals(roomShowVO.getName())) {
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean matches = pattern.matcher(roomShowVO.getName()).matches();
            StringBuilder  strb =new StringBuilder();
            if (matches) {
                int length = roomShowVO.getName().length();
                int a=4;
                if (length<a) {
                    for (int i = 0; i < a-length; i++) {
                        strb.append("0");
                    }
                    strb.append(roomShowVO.getName());
                    roomShowVO.setName(strb.toString());
                }
            }
        }
        //----------------------------------------------------------------------
        Room room = new Room();
        BeanUtils.copyProperties(roomShowVO,room);
        int count = roomService.getBaseMapper().updateById(room);
        if (count > 0){
            return CommonRes.ok();
        }
        return CommonRes.failed("修改房间信息失败");
    }

    @ApiOperation(value = "通过id删除房间")
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    @ApiImplicitParam(name = "id", value = "房间id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes delRoomById(@PathVariable Integer id) {
        List<Bed> beds = bedService.getBaseMapper().selectList(Wrappers.<Bed>lambdaQuery().eq(Bed::getRoomId, id));
        for (Bed b:beds) {
            Integer bedCount = radarBedService.getBaseMapper().selectCount(Wrappers.<RadarBed>lambdaQuery().eq(RadarBed::getBedId, b.getId()));
            if (bedCount > 0){
                return CommonRes.failed("该房间已有床位绑定监测仪，不能删除，如果想删除，请先解绑监测仪");
            }
        }
        Room room = roomService.getById(id);
        if (room == null) {
            return CommonRes.failed("该房间不存在");
        }
        int count = roomService.getBaseMapper().deleteById(id);
        if (count > 0){
            int deleteCnt = bedService.getBaseMapper().delete(Wrappers.<Bed>lambdaUpdate().eq(Bed::getRoomId, id));
            floorService.subBedCnt(room.getFloorId(), deleteCnt);
            buildingService.subBedCnt(room.getBuildingId(), deleteCnt);
            return CommonRes.ok();
        }
        return CommonRes.failed("删除房间信息失败");
    }


    @ApiOperation(value = "添加一个层床位数量")
    @PutMapping("/add/{id}")
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes addBedCnt(@PathVariable Integer id) {
        return roomService.addBedCnt(id);
    }


    @ApiOperation(value = "减少一个层床位数量")
    @PutMapping("/sub/{id}")
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes subBedCnt(@PathVariable Integer id) {
        return roomService.subBedCnt(id);
    }

    @ApiOperation(value = "通过层id查房间")
    @GetMapping("/getRoom/{floorId}")
    @ApiImplicitParam(name = "id", value = "层id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes getRoom(@PathVariable Integer floorId) {
        List<Room> rooms = roomService.getBaseMapper().selectList(Wrappers.<Room>lambdaQuery().eq(Room::getFloorId, floorId));
        Room room = new Room();
        room.setName("全部");
        rooms.add(0,room);
        return CommonRes.ok(rooms);
    }
}
